package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.common.util.IDGeneratorUtil;
import com.smarthospital.common.util.SHDateUtil;
import com.smarthospital.dao.daoService.HospitalDaoService;
import com.smarthospital.dao.daoService.UserDaoService;
import com.smarthospital.entity.dto.WxResultJscode2sessionDTO;
import com.smarthospital.entity.dto.YunSuoMallUserDTO;
import com.smarthospital.entity.pojo.Hospital;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.entity.vo.UserVO;
import com.smarthospital.entity.vo.WxAuthInfoVO;
import com.smarthospital.service.FileService;
import com.smarthospital.service.SHDictionaryService;
import com.smarthospital.service.UserService;
import com.smarthospital.web.inteceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 作    者： yingming shen
 * 修改时间： 2020/8/16 10:53.
 * 描   述：
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDaoService userDaoService;

    @Autowired
    private HospitalDaoService hospitalDaoService;

    @Autowired
    private SHDictionaryService dictionaryService;

    @Autowired
    private LoginServiceIpml loginService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private FileService fileService;

    @Value("${yunSuoMall.userInfo.url}")
    private String ysmUserInfoUrl;

    @Override
    public User getUser(){
        User user = userDaoService.selectById(LoginInterceptor.getUser().getId());
        boolean isDoctor = loginService.checkIsDoctor(user.getIdCardNum()) != null;
        user.setRole(isDoctor?1:0);
        return user;
    }

    @Override
    public User userInfo() {
        User user = userDaoService.selectById(LoginInterceptor.getUser().getId());
        user = dictionaryService.resolveUserDictionFields(user);
        boolean isDoctor = loginService.checkIsDoctor(user.getIdCardNum()) != null;
        user.setRole(isDoctor?1:0);
        return user;
    }

    @Override
    public void updateUserByWx(WxAuthInfoVO wxAuthInfoVO) {
        User user  = LoginInterceptor.getUser();
        String avatarUrl = wxAuthInfoVO.getAvatarUrl();

        String url = getHdfsUrl(avatarUrl);

        user.setNickName(wxAuthInfoVO.getNickName());
        user.setPicture(url);
        user.setGender(wxAuthInfoVO.getGender()+"");
        user.setAuthed(1);
        userDaoService.update(user);
    }

    @Override
    public User getByUnionId(String unionId) {
        return  userDaoService.selectByUnionid(unionId);
    }

    /**
     * 将腾讯头像存到hdfs服务器
     * @param avatarUrl
     * @return
     */
    private String getHdfsUrl(String avatarUrl) {
        String url = null;
        ByteArrayInputStream inputStream = null;
        try {
            ResponseEntity<byte[]> forEntity = restTemplate.getForEntity(avatarUrl, byte[].class );
            byte[] body = forEntity.getBody();
            inputStream = new ByteArrayInputStream(body);
            url = fileService.upload(inputStream,  "JPEG", body.length);
        } catch (Exception e) {
            log.error("updateUserByWx err {}",e.getMessage(),e);
        }finally {
            if (inputStream !=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("updateUserByWx err {}",e.getMessage(),e);
                }
            }
        }
        return url;
    }


    @Override
    public void updateUser(UserVO user) {
//        //校验短信
//        String code = user.getCode();
//        if (StringUtils.isEmpty(code)||StringUtils.isEmpty(user.getCheckPhone())) {
//            throw new CommonException(CodeMsg.ERROR_OPT_MISS);
//        }
        //不报错就是通过
//        optService.checkCode(LoginInterceptor.getUser().getId(),user.getCheckPhone(),SenceTypeEnum.SENCE_TYPE_0.getType(),code);
       //更新数据
        if (user.getId() == null) {
            throw new CommonException(CodeMsg.ERROR_PARAM);
        }
        userDaoService.update(user);
    }

    /**
     * 查询商城是否有此用户
     * @param wxResultJscode2sessionDTO
     * @return
     */
    public User initUser(WxResultJscode2sessionDTO wxResultJscode2sessionDTO) {

        User user = User.builder()
                //生成注册id
                .registerId(IDGeneratorUtil.getRegistId())
                .oppenId(wxResultJscode2sessionDTO.getOpenid())
                .unionId(wxResultJscode2sessionDTO.getUnionid())
                .createTime(SHDateUtil.now_yyyMMddHHmmss())
                .updateTime(SHDateUtil.now_yyyMMddHHmmss())
                .creator("self")
                .updator("self")
                .build();
        //查询商城用户资料
        YunSuoMallUserDTO userDTO = getYunSuoMallUser(wxResultJscode2sessionDTO.getUnionid());
        if (null != userDTO) {
            user.setGender(userDTO.getSex()+"");
            user.setNickName(userDTO.getNickname());
            user.setPicture(userDTO.getAvatar());
            user.setPhone(userDTO.getPhone());
            if (StringUtils.isNotBlank(userDTO.getCardId())) {
                user.setCertificateType(0);
                user.setIdCardNum(userDTO.getCardId());
            }
            user.setIdCardName(userDTO.getRealName());
            user.setCountry(userDTO.getCountry());
            user.setAddr(userDTO.getAddres());
        }
        userDaoService.insertSelective(user);
        return user;
    }

    /**
     * 查询商城用户
     * @param
     * @return
     */
    private YunSuoMallUserDTO getYunSuoMallUser(String unionid) {
        YunSuoMallUserDTO userDTO = null;
        try {
            userDTO = restTemplate.getForObject(String.format(ysmUserInfoUrl,unionid) , YunSuoMallUserDTO.class);
            log.info("【查询云索商城用户】 param {}  out {}",unionid, JSON.toJSONString(userDTO));
        } catch (Exception e) {
            log.error("【查询云索商城用户信息报错】 param {}  err {}",unionid,e.getMessage(),e);
        }
        return userDTO;
    }


    @Override
    public PageInfo<Hospital> querHospitals(Integer pageSize, Integer pageNum) {
        return hospitalDaoService.querHospitals(pageSize,pageNum);
    }

}
